<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>碰壁反弹</title>
    <style>
        #outer{
            width: 900px;
            height: 400px;
            background-color: #ccc;
            position: relative;
            margin: 0 auto;
            border:1px solid #000;
        }
        #box{
            width: 50px;
            height: 50px;
            background-color: indianred;
            position: absolute;
            left: 30px;
            top: 60px;
        }
    </style>
</head>
<body>
<div id="outer">
    <div id="box">

    </div>
</div>
<script>
    var oOuter = document.getElementById("outer");
    var oBox = document.getElementById("box");
    var timer = null;
    // 定义一个变量 保存x轴的位置
    var leftPoint = 30,topPoint = 60;
    //定义一个开关，如果目前向右走  那么值为true
    var isRight = true,isBottom = true;
    timer = setInterval(function () {
        if (isRight) {
            leftPoint ++;
            // 父级的宽度 减去 box 的宽度 就是box向右走最大的距离  临界值
            if (leftPoint >= oOuter.clientWidth - oBox.offsetWidth) {
                isRight = !isRight;
            }
        }else{
            leftPoint --;
            if (leftPoint <= 0){
                isRight = !isRight;
            }
        }


        if (isBottom) {
            topPoint ++;
            // 父级的宽度 减去 box 的宽度 就是box向右走最大的距离  临界值
            if (topPoint >= oOuter.clientHeight - oBox.offsetHeight) {
                isBottom = !isBottom;
            }
        }else{
            topPoint --;
            if (topPoint <= 0){
                isBottom = !isBottom;
            }
        }
        oBox.style.left = leftPoint + "px";
        oBox.style.top = topPoint + "px";
    },1)
</script>
</body>
</html>